
class Admin::ProductCasesController < Admin::BaseController
  before_action :find_product_case, only: [:show, :edit, :update, :destroy]

  def index
    @product_cases = ProductCase.with_deleted.paginate(page: params[:page] || 1, per_page: params[:per_page] || 15).order('id DESC')
  end

  def new
    @product_case = ProductCase.new
  end

  def show
    respond_to do |format|
      format.json { render json: {status: 'ok', product_case: @product_case}}
    end
  end

  def create
    product_case_params = params.require(:product_case).permit!
    product_case_params[:product_ids] = product_case_params[:product_ids].split(',')
    @product_case = ProductCase.new(product_case_params)

    if @product_case.save
      flash[:notice] = "新建楼层成功"
      redirect_to admin_product_cases_path
    else
      flash[:notice] = "新建楼层失败"
      render action: :new
    end

  end

  def edit
    render action: :new
  end

  def update
    product_case_params = params.require(:product_case).permit!
    product_case_params[:product_ids] = product_case_params[:product_ids].split(',')
    @product_case.attributes = product_case_params

    if @product_case.save
      flash[:notice] = "修改楼层成功"
      redirect_to admin_product_cases_path
    else
      flash[:notice] = "修改楼层失败"
      render action: :edit
    end
  end

  def destroy
    begin
      @product_case.destroy
      flash[:notice] = "删除楼层成功"
      redirect_to admin_product_cases_path
    rescue
      flash[:notice] = "删除楼层失败"
      redirect_to :back
    end

  end

  private

  def find_product_case
    @product_case = ProductCase.find params[:id]
  end

end
